package com.molyfun.parents.view;

import android.content.Context;
import android.text.Editable;
import android.text.InputType;
import android.text.TextWatcher;
import android.util.AttributeSet;
import android.view.LayoutInflater;
import android.view.View;
import android.widget.EditText;
import android.widget.FrameLayout;
import android.widget.ImageView;

import com.molyfun.parents.R;
import com.molyfun.parents.view.common.MfEditText;

import butterknife.ButterKnife;
import butterknife.InjectView;

/**
 * Created by william(liuchao.hit@gmail.com).
 * Date:10/14/16.
 */
public class SinglineClearEditText extends FrameLayout implements View.OnClickListener, TextWatcher{

    @InjectView(R.id.edit_text)
    MfEditText mMfEditText;
    @InjectView(R.id.clear_btn)
    ImageView mClearBtn;

    private Context context;

    protected LayoutInflater layoutInflater;

    public SinglineClearEditText(Context context) {
        super(context);
        init(context);
    }

    public SinglineClearEditText(Context context, AttributeSet attrs) {
        super(context, attrs);
        init(context);
    }

    public SinglineClearEditText(Context context, AttributeSet attrs, int defStyleAttr) {
        super(context, attrs, defStyleAttr);
        init(context);
    }

    private void init(Context context){
        this.context = context;
        layoutInflater = LayoutInflater.from(context);
        layoutInflater.inflate(R.layout.view_singleline_clear_edittext, this);
        ButterKnife.inject(this);
        mClearBtn.setOnClickListener(this);
        mMfEditText.addTextChangedListener(this);
    }

    public EditText getEditText(){
        return mMfEditText;
    }

    public void clear(){
        mMfEditText.setText("");
    }

    public void setHint(String str){
        mMfEditText.setHint(str);
    }

    public void setIsPwd(){
        mMfEditText.setInputType(InputType.TYPE_CLASS_TEXT | InputType.TYPE_TEXT_VARIATION_PASSWORD);
    }

    public String getString(){
        return mMfEditText.getText().toString().trim();
    }

    @Override
    public void onClick(View v) {
        switch (v.getId()){
            case R.id.clear_btn:
                mMfEditText.setText("");
                break;
        }
    }

    @Override
    public void beforeTextChanged(CharSequence s, int start, int count, int after) {

    }

    @Override
    public void onTextChanged(CharSequence s, int start, int before, int count) {

    }

    @Override
    public void afterTextChanged(Editable s) {
        if(s.length() > 0){
            mClearBtn.setVisibility(View.VISIBLE);
        }else{
            mClearBtn.setVisibility(View.GONE);
        }
    }
}